﻿using UnityEngine;
using TMPro;

public class ScoresReader : MonoBehaviour
{
    [SerializeField] private TMP_Text displayText;
    private const string ScoresKey = "TopStepScores";

    private void Start()
    {
        if (displayText == null)
        {
            Debug.LogError("displayText (TMP_Text) 未绑定！");
            return;
        }

        string data = PlayerPrefs.GetString(ScoresKey, "");
        if (string.IsNullOrEmpty(data))
        {
            displayText.text = "当前无历史记录";
            Debug.Log("PlayerPrefs里无排行榜数据");
            return;
        }

        var scores = new System.Collections.Generic.List<int>();
        foreach (var s in data.Split(','))
        {
            if (int.TryParse(s, out int step))
                scores.Add(step);
        }

        if (scores.Count == 0)
        {
            displayText.text = "当前无有效历史记录";
            Debug.LogWarning("解析出的排行榜为空");
            return;
        }

        scores.Sort();
        int count = Mathf.Min(scores.Count, 10);

        var sb = new System.Text.StringBuilder("历史步数前十：\n");
        for (int i = 0; i < count; i++)
        {
            sb.AppendLine($"{i + 1}. {scores[i]} 步");
        }

        displayText.text = sb.ToString();
        Debug.Log("排行榜显示内容:\n" + sb.ToString());
    }
}
